package backend;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class BackendServer {
    private static final int PORT = 8081;
    private static final String VIDEO_DIRECTORY = "videos";
    private static final Map<String, String> VIDEO_DB = new HashMap<>();

    static {
        VIDEO_DB.put("1", "sample1.mp4");
        VIDEO_DB.put("2", "sample2.mp4");
    }

    public static void main(String[] args) {
        // 创建视频目录（如果不存在）
        new File(VIDEO_DIRECTORY).mkdirs();

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("后台服务器启动，监听端口: " + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket clientSocket) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             OutputStream out = clientSocket.getOutputStream()) {

            String requestLine = in.readLine();
            if (requestLine == null) return;

            System.out.println("收到请求: " + requestLine);
            String[] requestParts = requestLine.split(" ");
            String method = requestParts[0];
            String path = requestParts[1];

            if (method.equals("GET") && path.equals("/videos")) {
                // 返回视频列表
                String response = String.join(",", VIDEO_DB.keySet());
                sendResponse(out, "200 OK", "text/plain", response.getBytes());
            } else if (method.equals("GET") && path.startsWith("/video/")) {
                // 返回特定视频
                String videoId = path.substring(7);
                String videoFile = VIDEO_DB.get(videoId);
                if (videoFile != null) {
                    Path videoPath = Paths.get(VIDEO_DIRECTORY, videoFile);
                    if (Files.exists(videoPath)) {
                        byte[] videoData = Files.readAllBytes(videoPath);
                        sendResponse(out, "200 OK", "video/mp4", videoData);
                    } else {
                        sendResponse(out, "404 Not Found", "text/plain", "Video file not found".getBytes());
                    }
                } else {
                    sendResponse(out, "404 Not Found", "text/plain", "Video not found".getBytes());
                }
            } else {
                sendResponse(out, "404 Not Found", "text/plain", "Not Found".getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void sendResponse(OutputStream out, String status, String contentType, byte[] content) throws IOException {
        String responseHeader = "HTTP/1.1 " + status + "\r\n" +
                "Content-Type: " + contentType + "\r\n" +
                "Content-Length: " + content.length + "\r\n" +
                "\r\n";
        out.write(responseHeader.getBytes());
        out.write(content);
        out.flush();
    }
}
